from flask import Flask, request
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from book_spider import get_book_catalog, parse_data, get_book_detail
from wechatpy.replies import TextReply, ImageReply
from wechatpy import parse_message
from io import StringIO
import xmltodict
import time


app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask网站首页'


@app.route('/test/', methods=['GET', 'POST'])
def test():

    if request.method == 'GET':
        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        echostr = request.args.get('echostr')

        print(signature, timestamp, nonce, echostr)

        try:
            check_signature('12345678', signature, timestamp, nonce)
        except InvalidSignatureException:
            return '非法请求'

        return echostr if echostr else '接口测试成功'
    else:
        xml_str = request.data
        print(xml_str)
        if not xml_str:
            return ""
        # 对xml字符串进行解析
        xml_dict = xmltodict.parse(xml_str)
        xml_dict = xml_dict.get("xml")

        # 提取消息类型
        msg_type = xml_dict.get("MsgType")
        if msg_type == "text":
            user_input = xml_dict.get("Content")
            if user_input == '1':
                content = get_book_catalog()
                fp = StringIO(content)
                items = parse_data(fp)
                res = '回复对应数字: 获取图书详情信息'
                for item in items:
                    item = item['catalog_id'] + '-' + item['catalog_title'] + '\n'
                    res += item
            else:
                books = get_book_detail(user_input)
                res = '书籍推荐如下:\n'
                for index, book in enumerate(books):
                    title = book.find("title").text
                    res += '%s.' % (index+1) + title + '\n'

            # 表示发送的是文本消息
            # 构造返回值，经由微信服务器回复给用户的消息内容
            resp_dict = {
                "xml": {
                    "ToUserName": xml_dict.get("FromUserName"),
                    "FromUserName": xml_dict.get("ToUserName"),
                    "CreateTime": int(time.time()),
                    "MsgType": "text",
                    "Content": res
                    # "Content": "you say:" + xml_dict.get("Content")
                }
            }
            # 将字典转换为xml字符串
            resp_xml_str = xmltodict.unparse(resp_dict)
            # 返回消息数据给微信服务器
            return resp_xml_str
        else:

            # resp_dict = {
            #     "xml": {
            #         "ToUserName": xml_dict.get("FromUserName"),
            #         "FromUserName": xml_dict.get("ToUserName"),
            #         "CreateTime": int(time.time()),
            #         "MsgType": "image",
            #         "MediaId": xml_dict.get("MediaId")
            #     }
            # }
            # resp_xml_str = xmltodict.unparse(resp_dict)
            # print(xml_dict.get("MediaId"))
            # # 返回消息数据给微信服务器
            # return resp_xml_str
            # msg = parse_message(xml_str)
            # reply = ImageReply(message=msg)
            # reply.media_id = xml_dict.get("MediaId")
            # xml = reply.render()
            return ''


if __name__ == '__main__':
    app.run()

# import falcon
# from falcon import uri
# from wechatpy.utils import check_signature
# from wechatpy.exceptions import InvalidSignatureException
#
#
# class Connect(object):
#
#     def on_get(self, req, resp):
#         query_string = req.query_string
#         query_list = query_string.split('&')
#         b = {}
#         for i in query_list:
#             b[i.split('=')[0]] = i.split('=')[1]
#
#         try:
#             check_signature(token='这里填写配置界面你输入的token', signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce'])
#             resp.body = (b['echostr'])
#         except InvalidSignatureException:
#             pass
#         resp.status = falcon.HTTP_200
#
#
# app = falcon.API()
# connect = Connect()
# app.add_route('/connect', connect)




